import { closeDB, getDB } from "@/utils/db";
import { newId } from "@/utils/id";
import { DEFAULT_PAGE_SIZE, newPagination } from "@/utils/pagination";
import { err, ok } from "@/utils/resp";
import { NextRequest } from "next/server";

export async function GET(req: NextRequest) {
  try {
    const pageStr = req.nextUrl.searchParams.get("page") || "0";
    const page = parseInt(pageStr, 10) || 0;

    const keyword = req.nextUrl.searchParams.get("keyword") || "";

    const where: string[] = [];
    const params: (string | number)[] = [];

    if (keyword) {
      where.push(" AND name LIKE '%' || ? || '%'");
      params.push(`${keyword}`);
    }

    const sql = `SELECT id, "type", name, host, port, password, "path" FROM nodes WHERE 1=1 ${where.join(
      ""
    )} ORDER BY id DESC LIMIT ${DEFAULT_PAGE_SIZE} OFFSET ${
      DEFAULT_PAGE_SIZE * page
    }`;

    const countSql = `SELECT COUNT(*) AS num FROM nodes WHERE 1=1 ${where.join(
      ""
    )}`;
    const db = await getDB();
    const nodes: SubmeNode[] = await db.all(sql, ...params);
    const count: Count = (await db.get(countSql, ...params)) || { num: 0 };
    await closeDB();
    return ok(newPagination(count.num, page, nodes));
  } catch (e) {
    return err(e as Error);
  }
}
export async function POST(req: Request) {
  try {
    const node: SubmeNode = await req.json();
    node.id = newId();
    const db = await getDB();
    await db.run(
      `INSERT INTO nodes (id, "type", name, host, port, password, "path") VALUES(?,?,?,?,?,?,?)`,
      node.id!,
      node.type,
      node.name,
      node.host,
      node.port,
      node.password,
      node.path
    );
    await closeDB();
    return ok(node);
  } catch (e) {
    return err(e as Error);
  }
}
export async function PUT(req: Request) {
  try {
    const node: SubmeNode = await req.json();
    if (!node.id) {
      throw new Error("请指定ID");
    }
    const db = await getDB();
    const r = await db.run(
      `UPDATE nodes SET  "type"=?, name=?, host=?, port=?, password=?, "path"=? WHERE id=?`,
      node.type,
      node.name,
      node.host,
      node.port,
      node.password,
      node.path,
      node.id!
    );
    await closeDB();
    return ok({ node, aff: r.changes });
  } catch (e) {
    return err(e as Error);
  }
}
